﻿using Core.Framework;
using iTool.ClusterComponent;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace DotNetty.OrleansClient
{
    public class iToolConnectorProvider
    {


        private iToolClusterHostClient clusterHostClient;

        public iToolClusterHostClient GetClusterClient() => this.clusterHostClient;

        /// <summary>
        /// Builder
        /// </summary>
        /// <returns></returns>
        public async Task<iToolClusterHostClient> CreateICluster()
        {

            iToolClientBuilder builder = default;

#if DEBUG
            builder = this.Debug_iToolClientBuilder();
#else

            builder = this.Release_iToolClientBuilder();
#endif

            Console.WriteLine("\niTool> Start connection...");
            try
            {
                this.clusterHostClient = await builder.BuildAndConnectAsync();
                CLog.WriteLineSuccess("iTool> Start connection success.");
                return this.clusterHostClient;
            }
            catch (Exception ex)
            {
                CLog.WriteLineError("iTool> Start Error :" + ex.Message);
                CLog.WriteLineError("iTool> Check 服务是否启动.");
                CLog.WriteLineError("iTool> Connection 连接失败.");
                throw new Exception(ex.Message);
            }
        }

        private iToolClientBuilder Debug_iToolClientBuilder()
        {
            var builder = new iToolClientBuilder();

            builder.UseAdoNetClustering(new AdoNetClusterOptions
            {
                AdoNetOptions = new AdoNetOptions
                {
                    DataSource = "10.0.1.9",
                    UID = "Gas_News",
                    PWD = "QGsga*!H0B1QXfPTo%tfNcc3e"
                },
                ClusterOptions = new ClusterIdentificationOptions(),
                ResponseTimeout = TimeSpan.FromSeconds(30)
            });

            return builder;
        }

        private iToolClientBuilder Release_iToolClientBuilder()
        {
            var builder = new iToolClientBuilder();

            builder.UseAdoNetClustering(new AdoNetClusterOptions
            {
                AdoNetOptions =
                    AppSetting.iToolConfigure.iToolBaseDatabaseList?.Any() == true ?
                        AppSetting.iToolConfigure.iToolBaseDatabaseList.First() :
                        new AdoNetOptions
                        {
                            DataSource = "127.0.0.1,2433",
                            UID = "sa",
                            PWD = "zhuJIAN320"
                        },
                ClusterOptions = new ClusterIdentificationOptions
                {
                    ClusterId = "iToolServiceCluster",
                    ServiceId = "iToolService"
                },
                ResponseTimeout = TimeSpan.FromSeconds(30)
            });

            return builder;
        }

    }
}
